package com.anlu.base.async.task;

import com.alibaba.ttl.TtlCallable;
import com.alibaba.ttl.TtlRunnable;
import com.anlu.base.exception.BaseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.function.Supplier;

/**
 * <p>
 * Description: 异步任务类
 * <p>
 * <p>
 *
 * @author anlu
 * @date 2024/9/23 10:01
 */
public class AsyncTask {
    private final Logger logger = LoggerFactory.getLogger(getClass());


    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;


    /**
     * 方法描述:  异步返回数据
     *
     * @param supplier .
     * @return java.util.concurrent.Future<T>
     * @author 安路路
     * @date 2024/9/23  10:08
     */
    public <T> Future<T> asyncSupplier(Supplier<T> supplier){

        Callable<T> cc = () -> {
            if(null == supplier){
                return null;
            }
            return supplier.get();
        };

        TtlCallable<T> tTtlCallable =TtlCallable.get(cc);
        Future<T> submit = taskExecutor.submit(tTtlCallable);

        return new MyFuture<T>(submit);

    }


    public <T> Future<T> asyncCallable(Callable<T> callable){
        Callable<T> cc = () -> {
            if(callable == null){
                return null;
            }
            try{
                return callable.call();
            } catch (Exception e){
                logger.error("asyncCallable error",e);
                throw new BaseException(e);
            }
        };
       TtlCallable<T> tTtlCallable = TtlCallable.get(cc);
       Future<T> submit = taskExecutor.submit(tTtlCallable);

       return new MyFuture<>(submit);
    }

    /**
     * 方法描述:  异步处理任务
     *
     * @param runnable .
     * @author 安路路
     * @date 2024/9/23  10:31
     */

    public void asyncRunable(Runnable runnable){
        Runnable rr = () -> {
            if(null == runnable){
              runnable.run();;
            }
        };

        TtlRunnable ttlRunnable = TtlRunnable.get(rr);
        taskExecutor.execute(ttlRunnable);
    }

}
